package com.example.distinguishcolors.adapter;

import android.content.Context;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.example.distinguishcolors.MainActivity;
import com.example.distinguishcolors.R;
import com.example.distinguishcolors.dao.GameRecordDao;
import com.example.distinguishcolors.domain.GameColor;
import com.example.distinguishcolors.domain.GameRecord;
import com.example.distinguishcolors.utils.ColorUtils;
import com.example.distinguishcolors.view.LyyDialog;
import com.litesuits.orm.LiteOrm;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Yingyong Lao
 * 创建时间 2021/10/2 13:40
 * @version 1.0
 */
public class ColorAdapter extends RecyclerView.Adapter<ColorAdapter.ViewHolder>{
    private List<GameColor> list;
    private MainActivity mainActivity;
    private int levelNum=1;//当前是第几关
    public static final int COLOR_DIS=100;
    private int dis=COLOR_DIS;//颜色差值
    private boolean isGameOver=false;//标志游戏是否已结束
    private boolean isNewRecord=false;//标志是否破纪录了
    private GameRecordDao dao=GameRecordDao.getInstance();
    private static final String TAG = "ColorAdapter";

    public ColorAdapter(List<GameColor> list,MainActivity activity) {
        this.list = list;
        mainActivity=activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View itemView = layoutInflater.inflate(R.layout.color_item,parent,false);
        ViewHolder viewHolder = new ViewHolder(itemView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        GameColor gameColor = list.get(position);
        holder.tv.setBackgroundColor(Color.parseColor(gameColor.getValue()));
        if(isGameOver&&gameColor.getType().equals(GameColor.SPECIAL)){
            holder.tv.setText("我在这");
        }else {
            holder.tv.setText("");
        }
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.tv.getLayoutParams();
        layoutParams.width=((getScreenWidth()-getPxFromDp(32))/4)-1;
        holder.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = gameColor.getType();
                if(mainActivity.isFirstTime()){
                    LyyDialog dialog=new LyyDialog(mainActivity,null);
                    dialog.setContent("游戏尚未开始，请点击“开始游戏”按钮。");
                    dialog.show();
                    return;
                }
                if(isGameOver){
                    LyyDialog dialog=new LyyDialog(mainActivity,null);
                    dialog.setContent("游戏已结束，请重新开始！");
                    dialog.show();
                    return;
                }
                if(mainActivity.isPause()){
                    LyyDialog dialog=new LyyDialog(mainActivity,null);
                    dialog.setContent("游戏暂停中，若想继续请点击“继续游戏”按钮。");
                    dialog.show();
                    return;
                }
                if(GameColor.NORMAL.equals(type)){//玩家点击错误
                    int specialColorIndex=0;
                    for (int i = 0; i < list.size(); i++) {
                        GameColor gameColor1 = list.get(i);
                        if(GameColor.SPECIAL.equals(gameColor1.getType())){
                            specialColorIndex=i;
                        }
                    }

                    ArrayList<GameRecord> allByOrder = dao.findAllByOrder();
                    if(allByOrder.size()==0){//没有记录也认为是破纪录了
                        isNewRecord=true;
                    }
                    if(allByOrder!=null&&allByOrder.size()>0){//先和第一名比较，如果破纪录了就提示玩家将大名留下来，否则使用默认的名称
                        GameRecord gameRecord = allByOrder.get(0);
                        int level = gameRecord.getLevel();//关卡
                        int spendTime = gameRecord.getSpendTime();//游戏所花费的时间
                        long timeMillis = gameRecord.getTimeMillis();//游戏记录时间
                        if((levelNum-1)>level){//破记录了
                            isNewRecord=true;
                        }else {
                            if((levelNum-1)==level){//关卡相等的情况还有希望破纪录，接下来就是比较花费的时间
                                long spT=mainActivity.getSpendT();
                                if(spT<spendTime){
                                    isNewRecord=true;
                                }else {
                                    if(spT==spendTime){//花费的时间相等也没关系，只要我的记录时间更新，就认为我的成绩更优秀
                                        isNewRecord= System.currentTimeMillis() > timeMillis;
                                    }else {
                                        isNewRecord=false;
                                    }
                                }
                            }else {
                                isNewRecord=false;
                            }
                        }
                    }
                    String dialogContent=isNewRecord?"选择错误，但恭喜大侠破纪录了，请留下您的大名吧！":"正确答案为第"+(specialColorIndex+1)+"个，您的选择有误，游戏结束！";
                    LyyDialog lyyDialog=new LyyDialog(mainActivity, new LyyDialog.SelectCallBack() {
                        @Override
                        public void onPositiveClick() {
                            isGameOver=true;
                            ArrayList<GameColor> gameColors=new ArrayList<>(list);
                            list.clear();
                            notifyDataSetChanged();
                            list.addAll(gameColors);
                            notifyDataSetChanged();

                            long spendT = mainActivity.getSpendT();
                            String playerN=isNewRecord?getNameEt().getText().toString():"普通玩家";//破纪录了才能自定义名称
                            GameRecord gameRecord=new GameRecord(playerN,(levelNum-1), (int) spendT,System.currentTimeMillis());
                            long save = dao.save(gameRecord);
                            Log.d(TAG, "onClick: "+"保存游戏记录成功！"+save);
                        }
                    },true,isNewRecord);
                    lyyDialog.setContent(dialogContent);
                    lyyDialog.show();
                    mainActivity.getGameHandler().removeMessages(MainActivity.NEXT);
                    mainActivity.getTimeTv().setText("游戏已结束...");
                    mainActivity.getPauseBtn().setEnabled(false);
                    mainActivity.getGameHandler().removeMessages(MainActivity.SPEND_TIME);
                }else if(GameColor.SPECIAL.equals(type)){//玩家点击正确
                    levelNum++;
                    if(dis>=2){//保证有最小的颜色差1
                        dis--;
                    }
                    Toolbar toolbar = mainActivity.toolbar;
                    toolbar.setSubtitle("第"+levelNum+"关");
                    list.clear();
                    list.addAll(ColorUtils.getRandomColors(dis));
                    notifyDataSetChanged();
                    MainActivity.GameHandler gameHandler = mainActivity.getGameHandler();
                    gameHandler.removeMessages(MainActivity.NEXT);
                    gameHandler.setCount(MainActivity.SELECT_TIME);
                    gameHandler.sendEmptyMessage(MainActivity.NEXT);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView tv;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv=itemView.findViewById(R.id.tv);
        }
    }

    /**
     * 获取屏幕的宽度
     * @return
     */
    private int getScreenWidth(){
        WindowManager manager = (WindowManager) mainActivity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics=new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    private int getPxFromDp(int dpValue){
        float density = mainActivity.getResources().getDisplayMetrics().density;
        return Math.round(density*dpValue);
    }

    public void setGameOver(boolean gameOver) {
        isGameOver = gameOver;
    }

    public void setDis(int dis) {
        this.dis = dis;
    }

    public void setLevelNum(int levelNum) {
        this.levelNum = levelNum;
    }
}
